#-*- coding:utf-8 -*-
from json.decoder import JSONDecodeError
from typing import Any

import requests
import json
from loguru import logger
import unittest
import datetime
from openpyxl import Workbook, load_workbook
from db.cloud import *


class DateEncoder(json.JSONEncoder):
    def default(self, o: Any) -> Any:
        if isinstance(o, datetime.datetime):
            return o.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, o)


def getCurrentTime():
    return datetime.datetime.now()


def get(url, data="", headers={"Content-Type": "application/x-www-form-urlencoded"}):
    """
    get请求，返回字典格式
    :param url:
    :param data:
    :param headers:
    :return:
    """
    logger.info(f"url: {url}, data:{data}")
    try:
        response = requests.get(url, params=data, headers=headers)
        if response:
            logger.info(f"response:{response.json()}")
        else:
            logger.error("response is None")
    except JSONDecodeError:
        logger.error("json格式转换错误")
        return response
    return response.json()


def post(url, data, headers={"Content-Type": "application/x-www-form-urlencoded"}):
    """
    入参是表单格式的post请求，返回字典格式
    :param url:
    :param data:
    :param headers:
    :return:
    """
    logger.info(f"url: {url}, data:{data}")
    response = requests.post(url, data=data, headers=headers)
    logger.info(f"response:{response.json()}")
    return response.json()


def postJSON(url, data, headers={"Content-Type": "application/json"}):
    """
    入参是json格式的post请求，返回字典格式
    :param url:
    :param data:
    :param headers:
    :return:
    """
    headers["Content-Type"] = "application/json"
    logger.info(f"url: {url}, data:{data}")
    response = requests.post(url, data=json.dumps(data, cls=DateEncoder), headers=headers)
    logger.info(f"response:{response.json()}")
    return response.json()


# def formatString(str1):
#     if str1.isdigit():
#         if type(eval(str1)) == int:
#             return int(str1)
#         elif type(eval(str1)) == float:
#             return float(str1)
#     else:
#         return str1

def readFile(fileName):
    """
    读取excel用例，返回数据元组，不包含第一行
    :param fileName:
    :return:
    """
    logger.info(f"fileName:{fileName}")
    resultList = []
    try:
        fileName = "../testcase/testExcel/" + fileName
        file = load_workbook(fileName)
        sheet = file["Sheet1"]
        cases = sheet.values
        for i in cases:
            # 更改元素数据类型
            listI = list(i)
            # for j in range(len(listI)):
            #     listI[j] = formatString(listI[j])

            resultList.append(listI)
        logger.info(f"excelData:{resultList}")
    except Exception as e:
        logger.error(e)
    return resultList[1:]

def insertAdmin(name, account,addId,birthday,card,cityId,companyId,contractTime, createTime, departmentId,
                email, entryTime, lastLoginTime, leaveTime, outDate, phone, positiveTime,
                productId, resetPwdTime, schedule, sex, status, validataCode):
    Admin.insert(account = account,
    add_id = addId,
    birthday = birthday,
    card = card,
    city_id = cityId,
    company_id = companyId,
    contract_time = contractTime,
    create_time = createTime,
    department_id = departmentId,
    email = email,
    entry_time = entryTime,
    last_login_time = lastLoginTime,
    leave_time = leaveTime,
    name = name,
    out_date = outDate,
    phone = phone,
    positive_time = positiveTime,
    product_id = productId,
    reset_pwd_time = resetPwdTime,
    schedule = schedule,
    sex = sex,
    status = status,
    validata_code = validataCode).execute()

def deleteAdmin(name):
    Admin.delete().where(Admin.name==name).execute()


def updateAdmin(name, addId="",birthday="",card="",cityId="",companyId="",contractTime="", createTime="", departmentId="",
                email="", entryTime="", lastLoginTime="", leaveTime="", outDate="", phone="", positiveTime="",
                productId="", resetPwdTime="", schedule="", sex="", status="", validataCode=""):
    dict = {}
    if addId:
        dict[Admin.add_id] = addId
    if birthday:
        dict[Admin.birthday] = birthday
    if card:
        dict[Admin.card] = card
    if cityId:
        dict[Admin.city_id] = cityId
    if companyId:
        dict[Admin.company_id] = companyId
    if contractTime:
        dict[Admin.contract_time] = contractTime
    if createTime:
        dict[Admin.create_time] = createTime
    if departmentId:
        dict[Admin.department_id] = departmentId
    if email:
        dict[Admin.email] = email
    if entryTime:
        dict[Admin.entry_time] = entryTime
    if lastLoginTime:
        dict[Admin.last_login_time] = lastLoginTime
    if leaveTime:
        dict[Admin.leave_time] = leaveTime
    if outDate:
        dict[Admin.out_date] = outDate
    if phone:
        dict[Admin.phone] = phone
    if positiveTime:
        dict[Admin.positive_time] = positiveTime
    if productId:
        dict[Admin.product_id] = productId
    if resetPwdTime:
        dict[Admin.reset_pwd_time] = resetPwdTime
    if schedule:
        dict[Admin.schedule] = schedule
    if sex:
        dict[Admin.sex] = sex
    if status:
        dict[Admin.status] = status
    if validataCode:
        dict[Admin.validata_code] = validataCode

    Admin.update(dict).where(Admin.name == name).execute()

def selectAdmin(name):
    return Admin.select().where(Admin.name == name).get()


def deleteUser(username):
    user = selectUser(username)
    if user:
        user.delete_instance(recursive=True)



def selectUser(username):
    try:
        user = User.select().where(User.username == username).get()
    except DoesNotExist:
        return None

    return user

deleteUser("liudehua")






